import os
import sys


def has_bom(file_path):
    """检查文件是否包含BOM (U+FEFF)"""
    with open(file_path, 'rb') as f:
        return f.read(3) == b'\xef\xbb\xbf'


def remove_bom(file_path):
    """移除文件的BOM头"""
    with open(file_path, 'rb') as f:
        content = f.read()
    if content.startswith(b'\xef\xbb\xbf'):
        with open(file_path, 'wb') as f:
            f.write(content[3:])
        return True
    return False


def process_directory(directory):
    """递归处理目录中的所有文件"""
    for root, _, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                if has_bom(file_path):
                    print(f"处理文件: {file_path}")
                    if remove_bom(file_path):
                        print(f"已移除BOM: {file_path}")
            except (IOError, UnicodeDecodeError) as e:
                print(f"跳过非文本文件或无法读取: {file_path} ({e})")


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("用法: python remove_bom.py <目录路径>")
        sys.exit(1)

    target_dir = sys.argv[1]
    if not os.path.isdir(target_dir):
        print(f"错误: 目录不存在: {target_dir}")
        sys.exit(1)

    print(f"开始处理目录: {target_dir}")
    process_directory(target_dir)
    print("BOM 清理完成！")